//支付弹窗
import React, { useState, useEffect, useRef } from 'react';
import { Card, message, Input, Alert } from 'antd';
import CommonModal from '@/components/CommonModal';
import IconFont from '@/components/IconFont';
import CommonLoading from '@/components/CommonLoading';
import { formatAmount } from '@/utils/utils';
import { getAccountBalanceOp } from '@/services/user';
import { ExclamationCircleFilled } from '@ant-design/icons';
import payConfig from './payConfig';
import api from './service';
import styles from './index.module.less';

export default ({ item, discount, handleOk, handleCancel, resetDisCount }) => {

	//支付场景以及是否需要用户主动选择支付
	const { sceneKey, needChoosePay, alipayState, payScene } = item;

	//当前支付场景需要的支付设置-包含请求接口、参数格式化、优惠券配置、支付描述等
	const currentPayConfig = payConfig[sceneKey];

	const { realPayApi, payDescTop, payDescBottom, formatParams, formatRealAmount, formatRealBalanceAmount, formatRealAliPayAmount } = currentPayConfig;

	//用户账户余额
	const [userBalance, setUserBalance] = useState(0);

	const [loading, setLoading] = useState(false);

	const initPayType = item.payScene || 1;

	//支付方式，1-余额  10-企业支付宝
	const [payType, setPayType] = useState(initPayType);

	//支付密码弹框
	const passwordRef = useRef('');

	//初始化获取账户余额
	useEffect(() => {
		getAccountBalance();
	}, []);

	//获取账户余额
	const getAccountBalance = async () => {
		const res = await getAccountBalanceOp();
		if (res.success) {
			setUserBalance(res.data.availBalance);
		}
	};

	//点击切换支付方式
	const handlePayType = val => {
		if (needChoosePay) {
			setPayType(val);
		}
	}

	//渲染余额图标
	const renderBalance = (isChecked) => {
		return (
			<Card className={styles.cardStyle} onClick={() => handlePayType(1)}>
				<div className={styles.absolutedCenter}>
					<IconFont type="iconyue" style={{ fontSize: '28px', marginRight: '12px' }}></IconFont>
					<div>
						<div className="common-color11" style={{ fontSize: '14px', lineHeight: '14px', marginBottom: '4px' }}>余额支付</div>
						<div className="common-color9" style={{ fontSize: '10px', lineHeight: '10px' }}>免手续费</div>
					</div>
				</div>
				{
					isChecked ?
						<div className={styles.checkedBox}>
							<IconFont type="iconxuanzhongjiaobiao" style={{ width: '18px', height: '16px' }} />
						</div>
						: null
				}
			</Card>
		)
	}

	//渲染支付宝图标
	const renderAliPay = (isChecked) => {
		return (
			<Card className={styles.cardStyle} onClick={() => handlePayType(10)}>
				<span className={styles.absolutedCenter}>
					<IconFont type="iconzhifubao" style={{ fontSize: '28px', marginRight: '12px' }} ></IconFont>
					<span className="common-color11" style={{ fontSize: '14px', lineHeight: '14px' }}>
						支付宝
					</span>
				</span>
				{
					isChecked ?
						<div className={styles.checkedBox}>
							<IconFont type="iconxuanzhongjiaobiao" style={{ width: '18px', height: '16px' }} />
						</div>
						: null
				}
			</Card>
		)
	}

	//渲染余额支付内容
	const renderBalanceMsg = (realAmount) => {
		const amount = formatAmount(realAmount || 0) < 0 ? 0 : formatAmount(realAmount || 0);
		return (
			<div className={styles.showTotal}>
				<div className="flex" style={{ marginBottom: '16px' }}>
					<span style={{ marginRight: '32px' }}>
						支付金额：<span className="common-color9"> {`￥${amount}`}</span>
					</span>
					<span>
						账户余额：<span className="common-color9">￥{formatAmount(userBalance || 0)}</span>
					</span>
				</div>
				<p>
					<span className="common-color11">支付密码：</span>
					<Input type="password" style={{ width: '80%' }} placeholder="请输入支付密码" autoComplete="new-password" ref={passwordRef} />
				</p>
			</div>
		)
	}

	//支付宝支付内容
	const renderAliPayMsg = (realAmount) => {
		const amount = formatAmount(realAmount || 0) < 0 ? 0 : formatAmount(realAmount || 0);
		return (
			<div className={styles.showTotal}>
				<div className="flex" style={{ marginBottom: '16px' }}>
					<span style={{ width: '40%' }}>
						支付金额：
						<span className="common-color9">
							{`￥${amount}`}
						</span>
					</span>
				</div>
			</div>
		)
	}

	//渲染描述内容
	const renderDesc = (desc) => {
		return (
			<div className={styles.descWrap}>
				<ExclamationCircleFilled className={styles.descIcon} />
				<span className={styles.descContent}>{desc}</span>
			</div>
		)
	}

	//点击确定支付
	const onOk = async () => {
		// const password = passwordRef.current.input.value.replace(/ /g, '');
		let password;
		if ((payType == 1 || payType == -1)) {
			if(passwordRef.current) {
				password = passwordRef.current.input.value;
				if(!password) {
					message.info('请填写支付密码');
					return;
				}
			}
		}
		handlePayOrder(password);
	};



	// 提交操作
	const handlePayOrder = async (password) => {
		if (discount?.member_coupon_id) {
			setLoading(true);
			const { success, data } = await api.validateCouponOp({
				expressCouponId: discount.member_coupon_id,
				orderId: item.ids
			})
			setLoading(false);
			if (!(success && data)) {
				resetDisCount();
				return;
			}
		}
		setLoading(true);
		const params = formatParams(item, payType, password, discount);
		const payApi = realPayApi(item);
		const { success, msg, data } = await payApi(params);
		setLoading(false);
		if (success) {
			switch (sceneKey) {
				case 'singlePayOrder': {
					handleOk(item.ids, 2);
					handleCancel && handleCancel();
					message.success(msg);
					break;
				}
				case 'splitOrderPay': {
					handleOk(data.idList);
					message.success('支付成功');
					break;
				}
				case 'errorChangePay':
				case 'mallErrorOrderPay': {
					if (item.current?.isChecked) {//自动取消异常
						await api.autoCancelErrorOp({ ids: item.current.ids, isAuto: 1 });
					}
					handleOk(item.ids);
					handleCancel();
					message.success('支付成功');
					break;
				}
				case 'oneKeyErrorGoodsPay': {
					handleOk(data);
					break;
				}
				default:
					handleOk();
					message.success('支付成功');
			}
		}
	};

	//需要主动选择支付的情况下
	if (needChoosePay) {
		//余额是否选中
		const isCheckBalance = payType == 1 ? true : false;

		//支付宝是否选中
		const isCheckAliPay = payType == 10 ? true : false;

		//计算折扣之后的金额以及不同场景进行字段兼容
		const realBalanceAmount = formatRealBalanceAmount(item, discount);

		const realAliPayAmount = formatRealAliPayAmount(item, discount);

		return (
			<CommonModal
				title="支付方式"
				visible={true}
				onCancel={handleCancel}
				width={520}
				onOk={onOk}
			>
				{
					payDescTop && <div style={{ marginBottom: '24px' }}>{renderDesc(payDescTop)}</div>
				}
				<div className={`common-color11 ${styles.cardTitleStyle}`}>支付方式</div>
				<div style={{ display: 'flex' }}>
					{renderBalance(isCheckBalance)}
					{alipayState && renderAliPay(isCheckAliPay)}
				</div>
				{
					isCheckBalance && renderBalanceMsg(realBalanceAmount)
				}
				{
					isCheckAliPay && renderAliPayMsg(realAliPayAmount)
				}
				{
					isCheckAliPay && payDescBottom && <div style={{ marginTop: '24px' }}>{renderDesc(payDescBottom)}</div>
				}
				<CommonLoading loading={loading} />
			</CommonModal>
		)
	}

	//自动选择余额支付
	if (payScene == 1) {
		//计算折扣之后的金额以及不同场景进行字段兼容
		const realAmount = formatRealAmount(item, discount);;
		return (
			<CommonModal
				title="支付方式"
				visible={true}
				onCancel={handleCancel}
				width={520}
				onOk={onOk}
			>
				{
					payDescTop && <div style={{ marginBottom: '24px' }}>{renderDesc(payDescTop)}</div>
				}
				<div className={`common-color11 ${styles.cardTitleStyle}`}>支付方式</div>
				{renderBalance(true)}
				{renderBalanceMsg(realAmount)}
				<CommonLoading loading={loading} />
			</CommonModal>
		)
	}

	//自动选择支付宝支付
	if (payScene == 10) {
		//计算折扣之后的金额以及不同场景进行字段兼容
		const realAmount = formatRealAmount(item, discount);
		return (
			<CommonModal
				title="支付方式"
				visible={true}
				onCancel={handleCancel}
				width={520}
				onOk={onOk}
			>
				{
					payDescTop && <div style={{ marginBottom: '24px' }}>{renderDesc(payDescTop)}</div>
				}
				<div className={`common-color11 ${styles.cardTitleStyle}`}>支付方式</div>
				{renderAliPay(true)}
				{renderAliPayMsg(realAmount)}
				{payDescBottom && <div style={{ marginTop: '24px' }}>{renderDesc(payDescBottom)}</div>}
				<CommonLoading loading={loading} />
			</CommonModal>
		)
	}

	if (payScene == -1) {
		//计算折扣之后的金额以及不同场景进行字段兼容
		const realAmount = formatRealAmount(item, discount);;
		return (
			<CommonModal
				title="支付方式"
				visible={true}
				onCancel={handleCancel}
				width={520}
				onOk={onOk}
			>
				{
					payDescTop && <div style={{ marginBottom: '24px' }}>{renderDesc(payDescTop)}</div>
				}
				<div className={`common-color11 ${styles.cardTitleStyle}`}>支付方式一</div>
				{renderBalance(true)}
				{renderBalanceMsg(realAmount[0])}
				<div style={{ marginTop: '32px' }} className={`common-color11 ${styles.cardTitleStyle}`}>支付方式二</div>
				{renderAliPay(true)}
				{renderAliPayMsg(realAmount[1])}
				<CommonLoading loading={loading} />
			</CommonModal>
		)
	}

	return (
		<CommonModal
			title="支付方式"
			visible={true}
			onCancel={handleCancel}
			width={520}
			onOk={onOk}
		>
			{
				payScene == 1 ?
					<>
						<div className={`common-color11 ${styles.cardTitleStyle}`}>支付方式</div>
						<div style={{ display: 'flex' }}>
							{renderBalance(isCheckBalance)}
							{alipayState && renderAliPay(isCheckAliPay)}
						</div>
						{
							isCheckBalance && renderBalanceMsg(realAmount)
						}
						{
							isCheckAliPay && renderAliPayMsg(realAmount)
						}
					</>

					:
					null
			}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};
